package com.example.pcbcsmbackend.service;

import com.example.pcbcsmbackend.entity.Admin;
import com.example.pcbcsmbackend.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class AdminService {
    
    @Autowired
    private AdminRepository adminRepository;
    
    // 管理员登录
    public Admin login(String username, String password) {
        Optional<Admin> adminOpt = adminRepository.findByUsername(username);
        if (adminOpt.isPresent()) {
            Admin admin = adminOpt.get();
            if (admin.getPassword().equals(password) && admin.getStatus() == 1) {
                // 更新最后登录时间
                admin.setLastLogin(LocalDateTime.now());
                adminRepository.save(admin);
                return admin;
            }
        }
        throw new RuntimeException("用户名或密码错误");
    }
    
    // 创建管理员
    public Admin createAdmin(String username, String password) {
        if (adminRepository.existsByUsername(username)) {
            throw new RuntimeException("管理员用户名已存在");
        }
        Admin admin = new Admin(username, password);
        return adminRepository.save(admin);
    }
    
    // 根据ID查找管理员
    public Optional<Admin> findById(Integer adminId) {
        return adminRepository.findById(adminId);
    }
} 